package com.service.impl;

import com.mapper.SysDeptMapper;
import com.pojo.SysDept;
import com.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysDeptServiceImpl implements SysDeptService {
    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return deptMapper.selectDeptList(dept);
    }
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList=new ArrayList<>();
        //保存部门ID的集合
        List<Long> tempList=new ArrayList<>();
        for (SysDept dept:depts) {
            tempList.add(dept.getDeptId());
        }
        for (SysDept dept:depts) {
//            如果是顶级结点，遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())){
                //递归查找子部门
                recursionFn(depts,dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()){
            returnList=depts;
        }
        return returnList;
    }

    @Override
    public List<SysDept> buildDeptTreeSelect(List<SysDept> depts) {
        return null;
    }

    /**
     * 递归列表
     */
    public void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 获取子节点
     * @param list
     * @param t
     * @return
     */
    public List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<SysDept>();
        for (SysDept n : list) {
            if (n.getParentId()!=null && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    public boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }

    @Override
    public int add(SysDept sysDept) {
        return deptMapper.add(sysDept);
    }

    @Override
    public int edit(SysDept dept) {
        return deptMapper.edit(dept);
    }

    @Override
    public int del(Integer id) {
        return deptMapper.del(id);
    }

    @Override
    public SysDept view(Integer id) {
        return deptMapper.view(id);
    }

    @Override
    public List<SysDept> list() {
        return deptMapper.list();
    }
}
